package zj.it.bhne.gridengineeringsurvey.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.offline.MKOLSearchRecord;
import com.baidu.mapapi.map.offline.MKOfflineMap;
import com.baidu.mapapi.map.offline.MKOfflineMapListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import zj.it.bhne.gridengineeringsurvey.BaseActivity;
import zj.it.bhne.gridengineeringsurvey.R;
import zj.it.bhne.gridengineeringsurvey.adapter.CityChildAdapter;
import zj.it.bhne.gridengineeringsurvey.entity.OffLinebBean;

public class MainActivityExPanderListView extends BaseActivity implements MKOfflineMapListener {
    ExpandableListView mElv;
    private ExpandableListViewAdapter mExpandableListViewAdapter;
    private ArrayList<Object> mHeadertop;
    private MKOfflineMap mOffline = null;
    private TextView cidView;
    private TextView stateView;
    private EditText cityNameView;
    private ArrayList<String> hotCityNames;
    private ArrayList<String> hotCities;
    ArrayList<OffLinebBean> mDatas;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_ex_pander_list_view);
        try {
            mOffline = new MKOfflineMap();
            mOffline.init(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        initView();
    }
    private void initView() {
        cidView = (TextView) findViewById(R.id.cityid);
        cityNameView = (EditText) findViewById(R.id.city);
        stateView = (TextView) findViewById(R.id.state);
        View headerView = LayoutInflater.from(this).inflate(R.layout.exlistview_header, null);
        mElv = findViewById(R.id.expandableListView);


        //TODO 获取热门城市列表
        ListView hotCityList = (ListView) headerView.findViewById(R.id.hotcitylist);
        hotCities = new ArrayList<String>();
        hotCityNames = new ArrayList<String>();
        final List<Integer> integerList = new ArrayList<>();
        // 获取热闹城市列表
        ArrayList<MKOLSearchRecord> records1 = mOffline.getHotCityList();
        if (records1 != null) {
            for (MKOLSearchRecord r : records1) {
                //V4.5.0起，保证数据不溢出，使用long型保存数据包大小结果
                hotCities.add(r.cityName + "(" + r.cityID + ")" + "   --"
                        + this.formatDataSize(r.dataSize));
                hotCityNames.add(r.cityName);
                integerList.add(r.cityID);
            }
        }
        //Log.e("size=",hotCities.size()+"");
        ListViewsExpanderTop hadapterss = new ListViewsExpanderTop(this);
        hotCityList.setAdapter(hadapterss);
        hotCityList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                cityNameView.setText(hotCityNames.get(i));
                cidView.setText(integerList.get(i) + "");
            }
        });


        //TODO 获取所有支持离线地图的城市
        mDatas = new ArrayList<>();
        ArrayList<MKOLSearchRecord> mrecord = mOffline.getOfflineCityList();
        if (mrecord != null) {
            //遍历所有的省城市
            for (int i = 0; i < mrecord.size(); i++) {
                OffLinebBean offLinebBean = new OffLinebBean();
                offLinebBean.cityName = mrecord.get(i).cityName;
                offLinebBean.cityId = mrecord.get(i).cityID;
                offLinebBean.cityInformessage = mrecord.get(i).cityName + "(" + mrecord.get(i).cityID + ")" + "   --" + this.formatDataSize(mrecord.get(i).dataSize);
                if (mrecord.get(i).childCities != null) {
                    if (mrecord.get(i).childCities.size() > 0) {//如果是省份那么有下面的市
                        for (int j = 0; j < mrecord.get(i).childCities.size(); j++) {
                            OffLinebBean.CityChilden cityChilden = new OffLinebBean.CityChilden();
                            cityChilden.cityChildId = mrecord.get(i).childCities.get(j).cityID;
                            cityChilden.cityChildName = mrecord.get(i).childCities.get(j).cityName;
                            cityChilden.cityChildInformessage = mrecord.get(i).childCities.get(j).cityName + "(" + mrecord.get(i).childCities.get(j).cityID+ ")" + "   --"
                                    + this.formatDataSize(mrecord.get(i).dataSize);
                            offLinebBean.citychildList.add(cityChilden);
                        }
                    }
                    mDatas.add(offLinebBean);
                }
            }
        }
        //TODO 获取全国离线地图，并展示在上面
        mExpandableListViewAdapter = new ExpandableListViewAdapter(this);
       // TextView en = new TextView(this);
        mElv.addHeaderView(headerView);
        mElv.setAdapter(mExpandableListViewAdapter);
        mElv.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent,
                                        View v, int groupPosition, long id) {
                Toast.makeText(MainActivityExPanderListView.this, mDatas.get(groupPosition).cityName, Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        mElv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent,
                                        View v, int groupPosition, int childPosition,
                                        long id) {
                Toast.makeText(MainActivityExPanderListView.this, "hahaww", Toast.LENGTH_SHORT).show();

                //Log.e("ss", "groupPosition=" + groupPosition+ ",childPosition=" + childPosition);
                return false;
            }
        });
        mElv.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                int count = mElv.getExpandableListAdapter().getGroupCount();
                for (int j = 0; j < count; j++) {
                    if (j != groupPosition) {
                        mElv.collapseGroup(j);
                    }
                }
            }
        });


    }
    @Override
    public void onGetOfflineMapState(int i, int i1) {

    }

    //头部适配器
    class ListViewsExpanderTop extends BaseAdapter {
        Context context;

        ListViewsExpanderTop(Context context) {
            this.context = context;
        }

        ;

        @Override
        public int getCount() {
            //Log.e("count",hotCities.size()+"");
            return hotCities.size();
        }

        @Override
        public Object getItem(int i) {
            return hotCities.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolderItmeTop vi;
            if (view == null) {
                vi = new ViewHolderItmeTop();
                view = LayoutInflater.from(context).inflate(R.layout.activity_about_lintop, null);
                vi.textView = view.findViewById(R.id.tv_content);
                view.setTag(vi);

            } else {
                vi = (ViewHolderItmeTop) view.getTag();
            }
            vi.textView.setText(hotCities.get(i));

            return view;
        }

        class ViewHolderItmeTop {
            TextView textView;
        }
    }
    class ExpandableListViewAdapter extends BaseExpandableListAdapter {

        LayoutInflater mInflater;
        Context context;

        public ExpandableListViewAdapter(Context context) {
            mInflater = LayoutInflater.from(context);
            this.context = context;
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return mDatas.get(groupPosition).citychildList.get(childPosition);
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return groupPosition;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {
            if (convertView == null) {
                mViewChild = new ViewChild();
                convertView = mInflater.inflate(R.layout.channel_expandablelistview_item, null);
                mViewChild.gridView = (ListView) convertView.findViewById(R.id.channel_item_child_gridView);
                convertView.setTag(mViewChild);
            } else {
                mViewChild = (ViewChild) convertView.getTag();
            }
            //Log.e("resultItem="+groupPosition,mDatas.get(groupPosition).citychildList.toString());
            CityChildAdapter cityChlder = new CityChildAdapter(mDatas.get(groupPosition).citychildList, context);
            mViewChild.gridView.setAdapter(cityChlder);
            setGridViewListener(mViewChild.gridView,groupPosition);
            mViewChild.gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));

            return convertView;
        }

        /**
         * 设置gridview点击事件监听
         *
         * @param gridView
         */
        private void setGridViewListener(final ListView gridView, final int groupid) {
            gridView.setOnItemClickListener(new ListView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    Toast.makeText(context,mDatas.get(groupid).citychildList.get(position).cityChildId+"",Toast.LENGTH_LONG).show();
                    cityNameView.setText(mDatas.get(groupid).citychildList.get(position).cityChildName);
                    cidView.setText(mDatas.get(groupid).citychildList.get(position).cityChildId + "");
                }
            });
        }

        /**
         * 设置gridview数据
         *
         * @param data
         * @return
         */
        private ArrayList<HashMap<String, Object>> setGridViewData(String[] data) {
            ArrayList<HashMap<String, Object>> gridItem = new ArrayList<HashMap<String, Object>>();
            for (int i = 0; i < data.length; i++) {
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("channel_gridview_item", data[i]);
                gridItem.add(hashMap);
            }
            return gridItem;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return 1;
        }

        @Override
        public Object getGroup(int groupPosition) {
            return mDatas.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return mDatas.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            if (convertView == null) {
                mViewChild = new ViewChild();
                convertView = mInflater.inflate(
                        R.layout.channel_expandablelistview, null);
                mViewChild.textView = (TextView) convertView
                        .findViewById(R.id.channel_group_name);
                mViewChild.imageView = (ImageView) convertView
                        .findViewById(R.id.channel_imageview_orientation);
                convertView.setTag(mViewChild);
            } else {
                mViewChild = (ViewChild) convertView.getTag();
            }

            if (isExpanded) {
                mViewChild.imageView
                        .setImageResource(R.drawable.expander_listclose);
            } else {
                mViewChild.imageView
                        .setImageResource(R.drawable.expander_listview);
            }
            mViewChild.textView.setText(mDatas.get(groupPosition).cityName);
            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        ViewChild mViewChild;

        class ViewChild {
            ImageView imageView;
            TextView textView;
            ListView gridView;
        }
    }
    /**
     * V4.5.0起，保证数据不溢出，使用long型保存数据包大小结果
     */
    @SuppressLint("DefaultLocale")
    public String formatDataSize(long size) {
        String ret = "";
        if (size < (1024 * 1024)) {
            ret = String.format("%dK", size / 1024);
        } else {
            ret = String.format("%.1fM", size / (1024 * 1024.0));
        }
        return ret;
    }
}


